<template>
  <el-dialog
    :title="idEdit ? '修改学科' : '新增学科'"
    :visible.sync="showDialog"
    width="450px"
    @close="onClose"
  >
    <el-form ref="fromRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="学科名称" size="small" prop="subjectName">
        <el-input
          v-model="formData.subjectName"
          placeholder="请输入学科名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
          v-model="formData.isFrontDisplay"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-col :span="5">
        <el-button @click="onClose">取消</el-button>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="onOk">确认</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { add, detail, update } from "@/api/hmmm/subjects";
export default {
  data() {
    return {
      // 控制弹框的显示与隐藏
      showDialog: false,
      // 表单数据对象
      formData: {
        subjectName: "",
        isFrontDisplay: 0,
      },
      // 定义规则
      rules: {
        subjectName: [
          { required: true, message: "请输入学科标签", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // 定义一个变量来代表编辑状态
    idEdit() {
      return !!this.formData.id;
    },
  },
  methods: {
    // 弹框编辑逻辑
    onClose() {
      // 初始化formData
      (this.formData = {
        subjectName: "",
        isFrontDisplay: 0,
      }),
        // 重置表单
        this.$refs.fromRef.resetFields();
      // 关闭弹框
      this.showDialog = false;
    },
    // 按钮确认
    onOk() {
      // 区分修改状态和添加状态
      const fn = this.idEdit ? update : add;
      // 表单校验
      this.$refs.fromRef
        .validate()
        // 校验通过
        .then(() => {
          // console.log(this.formData);
          // return add(this.formData);
          return fn(this.formData);
        })
        .then(() => {
          this.$message.success(this.idEdit ? "修改成功" : "新增成功");
          // 告诉父组件我成功了
          this.$emit("done");
          // 关闭弹框
          this.onClose();
        })
        // 校验不通过
        .catch(() => {
          console.log("校验不通过");
        });
    },
    async update(row) {
      // 完成回显
      const { data } = await detail(row);
      this.formData = data;
      // console.log(data);
      // 打开弹框
      this.showDialog = true;
    },
  },
};
</script>

<style scoped lang="less"></style>
